package com.wjd.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjd.common.utils.PageUtils;
import com.wjd.common.utils.Query;
import com.wjd.gulimall.product.dao.AttrGroupDao;
import com.wjd.gulimall.product.entity.AttrGroupEntity;
import com.wjd.gulimall.product.service.AttrGroupService;
import com.wjd.gulimall.product.service.CategoryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Long catelogId = (Long) params.getOrDefault("catelogId", 0L);
        String key = (String) params.get("key");
        String sidx = (String) params.get("sidx");
        String order = (String) params.get("order");
        LambdaQueryWrapper<AttrGroupEntity> query = new LambdaQueryWrapper<AttrGroupEntity>()
                .eq(!Objects.equals(0L, catelogId), AttrGroupEntity::getCatelogId, catelogId)
                .and(StringUtils.isNotBlank(key), wrapper -> wrapper
                        .eq(AttrGroupEntity::getAttrGroupId, key)
                        .or()
                        .like(AttrGroupEntity::getAttrGroupName, key))
                .last(StringUtils.isNotBlank(sidx), "ORDER BY " + params.get("sidx") + " " + order);
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params), query
        );

        return new PageUtils(page);
    }

    @Override
    public AttrGroupEntity info(Long attrGroupId) {
        // 1. 查询属性分组
        AttrGroupEntity attrGroupEntity = getById(attrGroupId);
        if (attrGroupEntity == null) {
            return null; // 或者抛出异常
        }
        // 2. 查询所属分类路径
        Long catelogId = attrGroupEntity.getCatelogId();
        List<Long> categoryPath = categoryService.getCategoryPath(catelogId);
        categoryPath = categoryPath == null ? new ArrayList<>() : categoryPath;
        attrGroupEntity.setCatelogPath(categoryPath);
        return attrGroupEntity;
    }

}